package com.kr.aia.powerrp.roleplay;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.kr.aia.powerrp.common.RecController;
import com.kr.aia.powerrp.common.commonUtil;
import com.kr.aia.powerrp.db.CustomerInfoVO;
import com.kr.aia.powerrp.db.RPGroupDBUtil;
import com.kr.aia.powerrp.db.RPGroupInfoVO;
import com.kr.aia.powerrp.db.UserDBUtil;
import com.kr.aia.powerrp.dropbox.DropBoxMain;
import com.kr.aia.powerrp.dropbox.DropBoxRP;
import com.kr.aia.powerrp.setting.CustomerListAdapter;
import com.kr.aia.powerrp.setting.SettingMain;
import com.kr.aia.powerrp.telephone.TADataVO;
import com.kr.aia.powerrp.R;

public class RPSetting extends Activity implements OnClickListener{
	private static final String TAG = "TARP";
	private RPGroupDBUtil rpGroupDataSource;
	private commonUtil comUtil;
	
	private ProgressDialog initDialog;
	private ArrayList<RPGroupInfoVO> rpGroupData1;
	private ArrayList<RPGroupInfoVO> rpGroupData2;
	private ArrayList<RPGroupInfoVO> rpGroupData3;
	
	private String rpGroupContent;
	
    private Button rp_setting_btn_home;
    private Button rp_setting_btn_new;
    private Button rp_setting_btn_save;
    private Button rp_setting_btn_savenew;
    
    private ImageButton rp_setting_btn_save_grp;
    private ImageButton rp_setting_btn_del_grp;
    
    private Button rp_setting_btn_del;
    private Button rp_setting_btn_dropbox;
    
    private Switch rp_setting_swtich;
    private ToggleButton rp_setting_grp1;
    private ToggleButton rp_setting_grp2;
    private ToggleButton rp_setting_grp3;
    
    private EditText rp_setting_text;
    private ListView rpListView;
    
    private ArrayList<RPDataVO> rpData;
    private ArrayAdapter<RPDataVO> rpDataAdapter;
    private ArrayAdapter<RPDataVO> rpDataGroupAdapter;
    private ArrayAdapter<RPDataVO> rpDataDeleteAdapter;
    
    
    private String dirName;
    private String dataPath;
    
    private int rp_setting_selected_grp = 1;
    private int rpDataOrder = 0;
    
    private Boolean isDelButtonPressed;
    
    @Override
    public void onResume(){
    	refreshRPData();
    	super.onResume();
    }
    
    @Override
    public void onDestroy(){
    	rpGroupDataSource.close();
    	Log.e("PRP", "DB CLOSED");
    	super.onDestroy();
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rp_setting);
        comUtil = new commonUtil();
        
        isDelButtonPressed = false;
        
        // 객체 등록
        rp_setting_btn_home		= (Button) findViewById(R.id.rp_setting_btn_home);
        rp_setting_btn_new		= (Button) findViewById(R.id.rp_setting_btn_new);
        rp_setting_btn_save		= (Button) findViewById(R.id.rp_setting_btn_save);
        rp_setting_btn_savenew	= (Button) findViewById(R.id.rp_setting_btn_savenew);
        rp_setting_btn_del		= (Button) findViewById(R.id.rp_setting_btn_del);
        rp_setting_btn_dropbox	= (Button) findViewById(R.id.rp_setting_btn_dropbox);
        rp_setting_btn_save_grp = (ImageButton) findViewById(R.id.rp_setting_btn_save_grp);
        rp_setting_btn_del_grp  = (ImageButton) findViewById(R.id.rp_setting_btn_del_grp);
        
        rp_setting_swtich		= (Switch) findViewById(R.id.rp_setting_swtich);
        rp_setting_grp1			= (ToggleButton) findViewById(R.id.rp_setting_grp1);
        rp_setting_grp2			= (ToggleButton) findViewById(R.id.rp_setting_grp2);
        rp_setting_grp3			= (ToggleButton) findViewById(R.id.rp_setting_grp3);
        
        rp_setting_grp1.setChecked(true);
        rp_setting_grp1.setEnabled(false);
        rp_setting_grp2.setEnabled(false);
        rp_setting_grp3.setEnabled(false);
        
        comUtil.makeDisabledButton(rp_setting_btn_save_grp, true);
        comUtil.makeDisabledButton(rp_setting_btn_del_grp, true);
        
        
        rp_setting_text			= (EditText) findViewById(R.id.rp_setting_text);
        rpListView				= (ListView) findViewById(R.id.rpListView);
        
        
        this.rpData = new ArrayList<RPDataVO>();
        
        dirName = "/powerRP/txt/rp";
        dataPath = Environment.getExternalStorageDirectory().getPath() + dirName;
        
        // 최초 실행시 폴더가 없으면 폴더 생성
        comUtil.isDirectory(dataPath);
        
        /*
        if(true){        	
        	File file = new File(dataPath);
        	int dirCount = 0;
        	int fileCount = 0;
        	
        	FileInputStream fis = null;
        	BufferedReader br = null;
        	String strLine, strValue = "";
        	
        	for(File dirFile : file.listFiles()) {
        	    if(dirFile.isDirectory()) {
        	        dirCount++;
        	    }
        	    if(dirFile.isFile()) {
        	        fileCount++;
        	        
        	        try {
	        	        fis = new FileInputStream(dataPath + "/" + dirFile.getName());
	    				br  = new BufferedReader(new InputStreamReader(fis));
	    				strValue = "";
	    				while( (strLine = br.readLine()) != null )
	    					strValue += strLine + "\n";
	    				
	    				this.rpData.add(new RPDataVO(dirFile.getName().substring(0, dirFile.getName().length()-4), strValue, 0));
        	        } catch (IOException e) {
        				Toast toast = Toast.makeText(getApplicationContext(), "파일 읽기 실패. 다시 시도하세요.", Toast.LENGTH_SHORT); 
        				toast.show();
        				finish();
        			}
        	    }
        	}
        }
        */
        
        rpGroupDataSource = new RPGroupDBUtil(this);
        rpGroupDataSource.open();
        
        rpGroupData1 = rpGroupDataSource.getAllData(1);
        rpGroupData2 = rpGroupDataSource.getAllData(2);
        rpGroupData3 = rpGroupDataSource.getAllData(3);
        
        
        rpDataAdapter = new RPDataListAdapter(this, R.layout.rp_setting_list_row, rpData);
        rpDataAdapter.setNotifyOnChange(true);
        
        rpDataDeleteAdapter = new RPDataDeleteListAdapter(this, R.layout.rp_setting_list_del_row, rpData);
        rpDataDeleteAdapter.setNotifyOnChange(true);
        
        rpDataGroupAdapter = new RPDataGroupListAdapter(this, R.layout.rp_setting_grp_list_row, rpData);
        rpDataGroupAdapter.setNotifyOnChange(true);
        
        rpListView.setAdapter(rpDataAdapter);
        
        
        rpListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	RPDataVO tmp = (RPDataVO)parent.getAdapter().getItem(position);
            	((RPDataListAdapter) rpDataAdapter).setSelectedItem(position);
            	rpDataAdapter.notifyDataSetChanged();
            	rp_setting_text.setText(tmp.getContent());
            }
        });
        
        rp_setting_swtich.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				// TODO Auto-generated method stub
				boolean on = ((Switch) arg0).isChecked();
				refreshRPData();
				
	            if (on) {
	            	if(rp_setting_selected_grp == 1){
	            		rpDataOrder = 0 + bindingRpGroupOrder(rpGroupData1);
	            	}
	            	if(rp_setting_selected_grp == 2){
	            		rpDataOrder = 0 + bindingRpGroupOrder(rpGroupData2);
	            	}
	            	if(rp_setting_selected_grp == 3){
	            		rpDataOrder = 0 + bindingRpGroupOrder(rpGroupData3);
	            	} 
	            	
	            	rp_setting_text.setText(rpGroupContent);
	            	
	            	rpListView.invalidateViews();
	            	rpListView.setAdapter(rpDataGroupAdapter);
	            	rpListView.setItemsCanFocus(true);
	            	rpListView.setOnItemClickListener(new OnItemClickListener() {
	                    @Override
	                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	                    	RPDataVO tmp = (RPDataVO)parent.getAdapter().getItem(position);
	                    	((RPDataGroupListAdapter) rpDataGroupAdapter).setSelectedItem(position);
	                    	
	                    	if(rpData.get(position).getOrder() < 1){
	                    		rpDataOrder++;
	                    		rpData.get(position).setOrder(rpDataOrder);
	                    	}
	                    	if(!rpData.get(position).isSelected){
	                    		rp_setting_text.setText(rp_setting_text.getText() + "\n\n[" + tmp.getTitle() + "]\n" + tmp.getContent());
	                    		rpData.get(position).isSelected = true;
	                    	}
	                    	rpDataGroupAdapter.notifyDataSetChanged();
	                    }
	                });
	            	
	            	
	            	rp_setting_grp1.setEnabled(true);
	                rp_setting_grp2.setEnabled(true);
	                rp_setting_grp3.setEnabled(true);
	                
	                rp_setting_text.setFocusable(false);
	                rp_setting_text.setFocusableInTouchMode(false);
	                
	                InputMethodManager imm = (InputMethodManager)getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
	                imm.hideSoftInputFromWindow(rp_setting_text.getWindowToken(), 0);
	                
	                comUtil.makeDisabledButton(rp_setting_btn_save_grp, false);
	                comUtil.makeDisabledButton(rp_setting_btn_del_grp, false);
	                
	                /*comUtil.makeDisabledButton(rp_setting_btn_new, true);
	                comUtil.makeDisabledButton(rp_setting_btn_save, true);
	                comUtil.makeDisabledButton(rp_setting_btn_savenew, true);*/
	            	
	            } else {
	            	rpListView.invalidateViews();
	            	rpListView.setAdapter(rpDataAdapter);
	            	rpListView.setOnItemClickListener(new OnItemClickListener() {
	                    @Override
	                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	                    	RPDataVO tmp = (RPDataVO)parent.getAdapter().getItem(position);
	                    	((RPDataListAdapter) rpDataAdapter).setSelectedItem(position);
	                    	rpDataAdapter.notifyDataSetChanged();
	                    	rp_setting_text.setText(tmp.getContent());
	                    }
	                });
	            	
	            	rp_setting_grp1.setEnabled(false);
	                rp_setting_grp2.setEnabled(false);
	                rp_setting_grp3.setEnabled(false);
	                
	                rp_setting_text.setFocusable(true);
	                //rp_setting_text.setClickable(true);
	                rp_setting_text.setFocusableInTouchMode(true);
	                
	                comUtil.makeDisabledButton(rp_setting_btn_save_grp, true);
	                comUtil.makeDisabledButton(rp_setting_btn_del_grp, true);
	                
	                /*comUtil.makeDisabledButton(rp_setting_btn_new, false);
	                comUtil.makeDisabledButton(rp_setting_btn_save, false);
	                comUtil.makeDisabledButton(rp_setting_btn_savenew, false);*/
	            }
			}
        });
        
        
        
        /*
        rp_setting_text.setOnEditorActionListener(new OnEditorActionListener() {
        	@Override
        	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
	            if (event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
	                InputMethodManager in = (InputMethodManager) getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
	                in.hideSoftInputFromWindow(rp_setting_text.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
	            }
	            return false;
	        }
	    });
	    */
        

        /*
        String[] names = new String[] {  };
        setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, android.R.id.text1, names));
        ListView listView = getListView();
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        
        
        setListAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1,items));
        */
        
        
        /*
       
        // 우측 리스트 세팅
        //ArrayList<TADataVO> taData = getTAData();
        ArrayList<Button> btArray = new ArrayList<Button>();
        
        LinearLayout taDataListLayout = (LinearLayout)findViewById(R.id.ta_data_list);
        
        
        for (int i = 0; i < taData.size(); i++) {
        	btArray.add(i, new Button(this));
        	btArray.get(i).setHeight(50);
        	btArray.get(i).setWidth(400);
        	btArray.get(i).setTag(i);
        	btArray.get(i).setOnClickListener(
	        	new View.OnClickListener() {
	        		public void onClick(View v) {
	        			//Log.e("button", "버튼눌림");
	        			//눌렀을시 할 행동
	        		}
	        	}
	        );
        	 
        	btArray.get(i).setText(taData.get(i).getTitle());
        	taDataListLayout.addView(btArray.get(i));
        }

        
        
        for(int i = 0 ; i < taData.size(); i++){
        	//findViewById(R.id.Button01 + i).setOnClickListener(MyListener); 
        }
        
		*/
        
        // 클릭 리스너 등록
        rp_setting_btn_home.setOnClickListener(this);
        rp_setting_btn_new.setOnClickListener(this);
        rp_setting_btn_save.setOnClickListener(this);
        rp_setting_btn_savenew.setOnClickListener(this);
        rp_setting_btn_del.setOnClickListener(this);
        rp_setting_btn_dropbox.setOnClickListener(this);
        
        rp_setting_grp1.setOnClickListener(this);
        rp_setting_grp2.setOnClickListener(this);
        rp_setting_grp3.setOnClickListener(this);
        
        rp_setting_btn_save_grp.setOnClickListener(this);
        rp_setting_btn_del_grp.setOnClickListener(this);
        
        // 클릭 효과 세팅
        /*rp_setting_btn_home.setOnTouchListener(new commonOnTouchListener());
        rp_setting_btn_new.setOnTouchListener(new commonOnTouchListener());
        rp_setting_btn_save.setOnTouchListener(new commonOnTouchListener());
        rp_setting_btn_savenew.setOnTouchListener(new commonOnTouchListener());*/
    }
    
    @Override
    public void onClick(View v){
    	switch(v.getId()){
    		case R.id.rp_setting_btn_home:
    			finish();
    			break;
    		case R.id.rp_setting_grp1:
    			rp_setting_selected_grp = 1;
    			rp_setting_grp1.setChecked(true);
                rp_setting_grp2.setChecked(false);
                rp_setting_grp3.setChecked(false);
                
    			//((RPDataGroupListAdapter) rpDataGroupAdapter).setSelectedItem(-6);
                for(int i = 0 ; i < rpData.size(); i++){
    				rpData.get(i).isSelected = false;
    			}
                rpDataOrder = 0 + bindingRpGroupOrder(rpGroupData1);
            	rpDataGroupAdapter.notifyDataSetChanged();
            	rp_setting_text.setText(rpGroupContent);
    			break;
			case R.id.rp_setting_grp2:
				rp_setting_selected_grp = 2;
				rp_setting_grp1.setChecked(false);
                rp_setting_grp2.setChecked(true);
                rp_setting_grp3.setChecked(false);
                
    			//((RPDataGroupListAdapter) rpDataGroupAdapter).setSelectedItem(-6);
    			for(int i = 0 ; i < rpData.size(); i++){
    				rpData.get(i).isSelected = false;
    			}
                rpDataOrder = 0 + bindingRpGroupOrder(rpGroupData2);
            	rpDataGroupAdapter.notifyDataSetChanged();
            	rp_setting_text.setText(rpGroupContent);
			    break;
			case R.id.rp_setting_grp3:
				rp_setting_selected_grp = 3;
				rp_setting_grp1.setChecked(false);
                rp_setting_grp2.setChecked(false);
                rp_setting_grp3.setChecked(true);
                
    			//((RPDataGroupListAdapter) rpDataGroupAdapter).setSelectedItem(-6);
    			for(int i = 0 ; i < rpData.size(); i++){
    				rpData.get(i).isSelected = false;
    			}
    			rpDataOrder = 0 + bindingRpGroupOrder(rpGroupData3);
            	rpDataGroupAdapter.notifyDataSetChanged();
            	rp_setting_text.setText(rpGroupContent);
                
				break;
			case R.id.rp_setting_btn_save_grp:
				RPGroupInfoVO rpGroupInfo; 
				
				//기존 정보 삭제 후 입력
				rpGroupDataSource.deleteRPGroup(rp_setting_selected_grp);
				ArrayList<RPGroupInfoVO> tmpArry = new ArrayList<RPGroupInfoVO>();
				
				for(int i = 0 ; i < rpData.size(); i++){
					if(rpData.get(i).getOrder() > 0){
						rpGroupInfo = new RPGroupInfoVO();
						rpGroupInfo.setGroupId(rp_setting_selected_grp);
						rpGroupInfo.setFileName(rpData.get(i).getTitle());
						rpGroupInfo.setFileOrder(rpData.get(i).getOrder());
						rpGroupDataSource.insertRPGroupInfo(rpGroupInfo, rp_setting_selected_grp);
						tmpArry.add(rpGroupInfo);
						Log.e("PRP", " 000000000 cur group : " + rp_setting_selected_grp);
					}
				}
				
				if(rp_setting_selected_grp == 1){
					rpGroupData1.clear();
					rpGroupData1 = tmpArry;
				}else if(rp_setting_selected_grp == 2){
					rpGroupData2.clear();
					rpGroupData2 = tmpArry;
				}else if(rp_setting_selected_grp == 3){
					rpGroupData3.clear();
					rpGroupData3 = tmpArry;
				}
				
				Toast.makeText(this, "그룹이 저장 되었습니다.", Toast.LENGTH_SHORT).show();
				break;
			case R.id.rp_setting_btn_del_grp:
				rpGroupDataSource.deleteRPGroup(rp_setting_selected_grp);
				
				for(int i = 0 ; i < rpData.size() ; i++){
					rpData.get(i).setOrder(0);
					rpData.get(i).isSelected = false;
				}
				rpDataOrder = 0;
				rpDataGroupAdapter.notifyDataSetChanged();
				
				//((RPDataGroupListAdapter) rpDataGroupAdapter).setSelectedItem(-9);
    			rpListView.invalidateViews();
    			rp_setting_text.setText("");
				break;
				
    		case R.id.rp_setting_btn_new:
    			((RPDataListAdapter) rpDataAdapter).setSelectedItem(-1);
    			rpListView.invalidateViews();
    			rp_setting_text.setText("");
    			break;
    		case R.id.rp_setting_btn_save:
    			int cur = ((RPDataListAdapter) rpDataAdapter).getSelectedItem();
    			
    			if(cur < 0){
    				Toast.makeText(getApplicationContext(), "수정할 항목을 선택하세요.", Toast.LENGTH_SHORT).show();
    			}else{
    				String curTitle = ((RPDataListAdapter) rpDataAdapter).getItem(cur).getTitle();
    				createNewRPFile("mod", curTitle, cur);
    			}
    			break;
    		case R.id.rp_setting_btn_savenew:
    			
    			if(rp_setting_text.getText().toString().equals("")){
    				Toast.makeText(getApplicationContext(), "내용이 없습니다.", Toast.LENGTH_SHORT).show();
    				break;
    			}
    			
    			final EditText input = new EditText(this);
    			
    			new AlertDialog.Builder(this)
    		    .setTitle("신규파일 생성")
    		    .setMessage("제목을 입력하세요.")
    		    .setView(input)
    		    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    		        public void onClick(DialogInterface dialog, int whichButton) {
    		            String titleValue = input.getText().toString();
    		            
    		            if(titleValue.equals("")){
    		            	Toast.makeText(getApplicationContext(), "제목을 입력하세요.", Toast.LENGTH_SHORT).show();
    		            }else{
    		            	createNewRPFile("new", titleValue, -1);
    		            }
    		        }
    		    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    		        public void onClick(DialogInterface dialog, int whichButton) {
    		            // Do nothing.
    		        }
    		    }).show();
    			
    			
    			break;
    		case R.id.rp_setting_btn_del:
    			if(!isDelButtonPressed){
    				Toast.makeText(getApplicationContext(), "삭제 할 파일을 선택 후 삭제 버튼을 한번 더 눌러주세요.", Toast.LENGTH_LONG).show();
    				isDelButtonPressed = true;
    				//refreshRPData();

    				rpListView.invalidateViews();
                	rpListView.setAdapter(rpDataDeleteAdapter);
                	//rpListView.setItemsCanFocus(true);
                	rpListView.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        	((RPDataDeleteListAdapter) rpDataDeleteAdapter).setSelectedItem(position);
                        	
                        	if(rpData.get(position).isSelected){
                        		rpData.get(position).isSelected = false;
                    		}else{
                    			rpData.get(position).isSelected = true;
                    			Log.e(TAG, "isSelected  " + rpData.get(position).isSelected);
                    		}
                        	
                        	rpDataDeleteAdapter.notifyDataSetChanged();
                        }
                    });
    			}else{
    				int cntSel = 0;
    				boolean deleted = false;
    				Log.e(TAG, "44444444444444  " + rpData.size());
    				for(int i = 0 ; i < rpData.size(); i++){
    					if(rpData.get(i).isSelected){
    						Log.e("RPPP", dataPath + "/" + rpData.get(i).getTitle() + ".txt");
    						
    						File file = new File(dataPath + "/" + rpData.get(i).getTitle() + ".txt");
    						deleted = file.delete();
    						
    						
    						if(!deleted){
    							break;
    						}
    						cntSel++;
    					}
    				}
    				
    				if(cntSel > 0){
	    				if(deleted){
	    					Toast.makeText(getApplicationContext(), "삭제 되었습니다.", Toast.LENGTH_SHORT).show();
	    				}else{
	    					Toast.makeText(getApplicationContext(), "삭제 실패. 다시 시도하세요.", Toast.LENGTH_SHORT).show();
	    				}
    				}
    				refreshRPData();

    				rpListView.invalidateViews();
	            	rpListView.setAdapter(rpDataAdapter);
	            	rpListView.setOnItemClickListener(new OnItemClickListener() {
	                    @Override
	                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	                    	RPDataVO tmp = (RPDataVO)parent.getAdapter().getItem(position);
	                    	((RPDataListAdapter) rpDataAdapter).setSelectedItem(position);
	                    	rpDataAdapter.notifyDataSetChanged();
	                    	rp_setting_text.setText(tmp.getContent());
	                    }
	                });
	            	isDelButtonPressed = false;
    			}
    			
    			break;
    		case R.id.rp_setting_btn_dropbox:
    			Intent dropbox_intent = new Intent(this, DropBoxRP.class);
    			dropbox_intent.putExtra("is_rp", true);
    			startActivityForResult(dropbox_intent, 500);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    			break;
    	}
    }
    
    public void refreshRPData(){
    	rpData.clear();
    	
    	File file = new File(dataPath);
    	int fileCount = 0;
    	
    	FileInputStream fis = null;
    	BufferedReader br = null;
    	String strLine, strValue = "";
    	
    	for(File dirFile : file.listFiles()) {
    	    
    	    if(dirFile.isFile()) {
    	    	
    	    	if(dirFile.getName().toString().contains("closing")){
    	    		continue;
    	    	}
    	    	
    	        fileCount++;
    	        
    	        try {
        	        fis = new FileInputStream(dataPath + "/" + dirFile.getName());
    				br  = new BufferedReader(new InputStreamReader(fis));
    				strValue = "";
    				while( (strLine = br.readLine()) != null )
    					strValue += strLine + "\n";
    				
    				this.rpData.add(new RPDataVO(dirFile.getName().substring(0, dirFile.getName().length()-4), strValue, 0));
    	        } catch (IOException e) {
    				Toast toast = Toast.makeText(getApplicationContext(), "파일 읽기 실패. 다시 시도하세요.", Toast.LENGTH_SHORT); 
    				toast.show();
    				finish();
    			} finally{
    				try {
						br.close();
						fis.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
    			}
    	    }
    	}
    }
    
    public int bindingRpGroupOrder(ArrayList<RPGroupInfoVO> rpGroupData){
    	int rpGroupDataSize = 0;
    	rpGroupContent = "";
    	if(rpGroupData != null){
    		rpGroupDataSize = rpGroupData.size();
    	}
    	
    	for(int i = 0; i < rpData.size(); i++){
    		rpData.get(i).setOrder(0);
        }
    	
    	for(int j = 0 ; j < rpGroupData.size() ; j++){
    		for(int i = 0; i < rpData.size(); i++){
	    		if(rpData.get(i).getTitle().equals(rpGroupData.get(j).getFileName())){
	    			rpData.get(i).setOrder(rpGroupData.get(j).getFileOrder());
	    			
	    			if( rpGroupData.get(j).getFileOrder() > 0){
	    				rpData.get(i).isSelected = true;
	    			}
	    			rpGroupContent += "[" + rpData.get(i).getTitle() + "]" + "\n" + rpData.get(i).getContent() + "\n\n";
	    		}
    		}
        }
    	
    	
    	return rpGroupDataSize;
    }
   
    public void createNewRPFile(String bz, String title, int idx){
    	try {
    		File file = new File(dataPath + "/" + title + ".txt");
    		
    		FileOutputStream fos = new FileOutputStream(file);
			fos.write(rp_setting_text.getText().toString().getBytes());
			fos.close();
			
			if(bz.equals("new")){
				this.rpData.add(new RPDataVO(title, rp_setting_text.getText().toString(), 0));
				((RPDataListAdapter) rpDataAdapter).setSelectedItem(-1);
				rpListView.invalidateViews();
				rp_setting_text.setText("");
			}else{
				this.rpData.get(idx).setContent(rp_setting_text.getText().toString());
			}
			
			rp_setting_text.clearFocus();
			Toast.makeText(getApplicationContext(), "저장 되었습니다.", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
			Toast.makeText(getApplicationContext(), "저장 실패. 다시 시도하세요.", Toast.LENGTH_SHORT).show(); 
		}
    }
    
}









